<template>
    <div class="account">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          style="margin:10px 0"
        >新增</el-button>
      <el-table :data="userShareConfigs" border>
        <el-table-column label="层级" align="center" prop="hierarchy" width="120" :show-overflow-tooltip="true"/>
        <el-table-column label="层级说明" align="left" prop="name" width="180" :show-overflow-tooltip="true"/>
        <el-table-column label="分佣比例" align="center" prop="dividendRatio" width="90"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.dividendRatio * 100 }} %
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit"
                       @click="editUserShareConfig(scope.row)">修改</el-button>
            <el-button type="text" v-if="maxUserHierarchy === scope.row.hierarchy" icon="el-icon-delete"
                       @click="deleteShareConfig(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

        <!-- 编辑层级 -->
        <el-dialog :title="userShareEditTitle" :visible.sync="userShareOpen" width="600px" :close-on-click-modal="false">
            <el-form :model="userShareForm" ref="userShareForm" label-position="right" label-width="160"
                :rules="userShareFormRules">
                <el-form-item label="层级名字" prop="name">
                    <el-input v-model="userShareForm.name" style="width: 400px"></el-input>
                </el-form-item>
                <el-form-item prop="dividendRatio">
                    <span slot="label">
                        <el-tooltip content="最大值为1, 输入0.01表示1%" placement="top">
                            <i class="el-icon-question"></i>
                        </el-tooltip>
                        分佣比例
                    </span>
                    <el-input-number v-model="userShareForm.dividendRatio" :precision="2" :step="0.01" :min="0" :max="1"
                        style="width: 400px"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveUserConfig">
                        确定
                    </el-button>
                    <!-- <el-button @click="userShareOpen = false">取消</el-button> -->
                    <el-button @click="closeDialog('userShareForm', 'userShareOpen')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog title="新增" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <!-- <el-form-item label="统一分红配置ID" prop="id">
                <el-input v-model="form.id" placeholder="请输入统一分红配置ID" type="number"/>
                </el-form-item> -->
                <el-form-item label="层级" prop="hierarchy">
                <el-input  v-model="form.hierarchy" placeholder="请输入层级" />
                </el-form-item>
                <el-form-item label="层级名" prop="name">
                <el-input  v-model="form.name" placeholder="请输入层级名" />
                </el-form-item>
                <el-form-item label="分红比例" prop="dividendRatio">
                <el-input type="number" :min="0" v-model="form.dividendRatio" placeholder="请输入分红比例" />
                </el-form-item>
                <!-- <el-form-item label="类型" prop="type">
                <el-select class="modal-input" v-model="form.type">
                    <el-option class="modal-input" v-for="(item, index) in typeList" :key="index" :label="item.label"
                            :value="item.value"
                    ></el-option>
                </el-select>
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm(form)">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
    </el-dialog>
    </div>
</template>

<script>
import { configList, addShareConfig, updateConfig, delConfig } from "@/api/setting/gradeRebate";

export default {
    name: "Index",
    data() {
        return {
            // 遮罩层
            loading: true,
            open:false,
            form:{},
            // typeList:[
            //     {
            //         label:'店铺',
            //         value:1
            //     },
            //     {
            //         label:'个人',
            //         value:1
            //     }
            // ],
            // 用户表格数据
            dataList: null,
            // 排序
            storeShareConfigs: [],
            storeShareForm: {},
            storeShareOpen: false,
            storeShareEditTitle: "",
            storeShareFormRules: {
                name: [
                    {
                        required: true,
                        message: "请输入层级名称",
                        trigger: "change,blur",
                    },
                ],
                dividendRatio: [
                    {
                        required: true,
                        message: "请输入抽成比例",
                        trigger: "change,blur",
                    },
                ],
            },

            userShareConfigs: [],
            userShareForm: {},
            userShareOpen: false,
            userShareEditTitle: "",
            userShareFormRules: {
                name: [
                    {
                        required: true,
                        message: "请输入层级名称",
                        trigger: "change,blur",
                    },
                ],
                dividendRatio: [
                    {
                        required: true,
                        message: "请输入返佣比例",
                        trigger: "change,blur",
                    },
                ],
            },
            //商铺等级列表
            storeLevelList: [],
            openStore: false,
            titleStore: '',
            // 表单参数
            storeForm: {

            },
            // 表单校验
            storeRules: {
                name: { required: true, message: '请输入店铺等级名称', trigger: 'blur' },
                icon: { required: true, message: '请上传店铺等级图标', trigger: 'blur' },
                upgradeConditionNum: { required: true, message: '请输入升级条件', trigger: 'blur' },
                ratio: [{ required: true, message: '请输入佣金比例', trigger: 'blur' },{ pattern: /^1|0|[0]{1}[.]{1}[0]*[1-9]+[0-9]*$/, message:"佣金比例范围0-1", trigger: ['blur', 'change'] }],
                minIncomeRatio: [{ required: true, message: '请输入最低收益比例', trigger: 'blur' },{ pattern: /^1|0|[0]{1}[.]{1}[0]*[1-9]+[0-9]*$/, message:"最低收益比例范围0-1", trigger: ['blur', 'change'] }],
                incomeRatio: [{ required: true, message: '请输入收益比例', trigger: 'blur' },{ pattern: /^1|0|[0]{1}[.]{1}[0]*[1-9]+[0-9]*$/, message:"收益比例范围0-1", trigger: ['blur', 'change'] }],
                // level: { required: true, message: '请输入等级', trigger: 'blur' },
                nextLevel: { required: true, message: '请选择下级ID', trigger: ['blur', 'change']},
                earnestMoney: [{ required: true, message: '请输入保证金', trigger: 'blur' }],
            },
            rules: {
                // id: [
                // { required: false, message: "统一分红配置ID不能为空", trigger: "blur" }
                // ],
                hierarchy: [
                { required: true, message: "层级不能为空", trigger: "blur" }
                ],
                name: [
                { required: true, message: "层级名不能为空", trigger: "blur" }
                ],
                dividendRatio: [
                { required: true, message: "分红比例不能为空", trigger: "blur" }
                ],
                type: [
                { required: true, message: "类型不能为空", trigger: "change" }
                ],
            },
        };
    },
    created() {
        this.getShareConfig(1);
    },
    computed: {
        maxStoreHierarchy() {
            let hierarchy = 0;
            for (let item of this.storeShareConfigs) {
                if (item.type === 0) {
                    if (item.hierarchy >= hierarchy) {
                        hierarchy = item.hierarchy;
                    }
                }
            }
            return hierarchy;
        },
        maxUserHierarchy() {
            let hierarchy = 0;
            for (let item of this.userShareConfigs) {
                if (item.type === 1) {
                    if (item.hierarchy >= hierarchy) {
                        hierarchy = item.hierarchy;
                    }
                }
            }
            return hierarchy;
        },
    },
    methods: {
        handleAdd(){
            this.form  = {
                hierarchy:null,
                name:null,
                dividendRatio:null,
            }
            this.open = true;
        },
            /** 提交按钮 */
        submitForm(row) {
        this.$refs["form"].validate(valid => {
            if (valid) {
                let obj = {
                // id:row.id,
                hierarchy:row.hierarchy,
                name:row.name,
                dividendRatio:row.dividendRatio,
                type:1,
                }
                console.log(obj);
                addShareConfig(obj).then((res) => {
                    this.open = false
                    this.$message({ type: "success", message: "添加成功！" });
                    this.getShareConfig(1);
                });
            
            }
        });
        },
        cancel(){
            this.open = false;
        },
        getShareConfig(type) {
            configList(type).then((res) => {
                this.userShareConfigs = res.data || [];
            });
        },
        addUserShareConfig() {
            this.userShareOpen = true;
            this.userShareEditTitle = "新增分佣层级";
            this.userShareForm = {};
        },
        editUserShareConfig(row) {
            this.userShareEditTitle = "修改分佣百分比";
            this.userShareForm = Object.assign({}, row);
            this.userShareOpen = true;
        },
        saveUserConfig() {
            this.$refs["userShareForm"].validate((valid) => {
                if (valid) {
                    if (this.userShareForm.id) {
                        // 修改
                        if (this.userShareForm.id != -1) {
                            //如果是总分红不校验
                            const total =
                                this.totalDividendRatio(this.userShareForm.hierarchy, "1") +
                                this.userShareForm.dividendRatio;
                            if (total > 1) {
                                this.$message({
                                    type: "error",
                                    message: "分佣百分比总和不能大于100%",
                                });
                                return;
                            }
                        }

                        updateConfig(this.userShareForm).then((res) => {
                            this.$message({ type: "success", message: "修改成功！" });
                            this.getShareConfig(1);
                            this.resetUserConfigForm();
                        });
                    } else {
                        // 新增
                        const total =
                            this.totalDividendRatio("1") + this.userShareForm.dividendRatio;
                        if (total > 1) {
                            this.$message({
                                type: "error",
                                message: "分佣百分比总和不能大于100%",
                            });
                            return;
                        }
                        this.userShareForm.hierarchy = this.maxUserHierarchy + 1;
                        this.userShareForm.type = 1;
                        addShareConfig(this.userShareForm).then((res) => {
                            this.$message({ type: "success", message: "添加成功！" });
                            this.getShareConfig(1);
                            this.resetUserConfigForm();
                        });
                    }
                }
            });
        },
        resetUserConfigForm() {
            this.userShareOpen = false;
            this.userShareForm = {};
            this.$refs["userShareForm"].resetFields();
            this.$refs["userShareForm"].clearValidate();
        },
        deleteShareConfig(row) {
            this.$modal
                .confirm("确认删除" + row.hierarchy + "的数据项？")
                .then(function () {
                    return delConfig(row.id);
                })
                .then(() => {
                    this.getShareConfig(row.type);
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },

        totalDividendRatio(hierarchy, type) {
            if (type == "0") {
                let total = 0;
                for (let item of this.storeShareConfigs) {
                    if (hierarchy && hierarchy === item.hierarchy) {
                        continue;
                    }
                    total += item.dividendRatio;
                }
                return total;
            } else {
                let total = 0;
                for (let item of this.userShareConfigs) {
                    if (hierarchy && hierarchy === item.hierarchy) {
                        continue;
                    }
                    total += item.dividendRatio;
                }
                return total;
            }
        },
        closeDialog(form, open) {
            this.$refs[form].resetFields();
            this.$refs[form].clearValidate();
            this[open] = false;
        },
    },
};
</script>
<style scoped lang="scss">
.account{
  margin: 20px;
}
</style>
